package wnhz.com.business.shareshop.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.shareshop.bean.BankListBean;
import wnhz.com.business.uitls.Base64Util;
import wnhz.com.business.uitls.CustomerKeyboard;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.PasswordEditText;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.uitls.dialog.CommonDialog;
import wnhz.com.business.uitls.imgselect.BitnapUtils;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 共享商城提现
 */
public class TiXianActivityS extends BaseActivity implements View.OnClickListener,ActionBarClickListener {

    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.tv_bankname)
    TextView tvBankname;
    @BindView(R.id.tv_cardnum)
    TextView tvCardnum;
    @BindView(R.id.ll_addcard)
    LinearLayout llAddcard;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_allmoney)
    TextView tvAllmoney;
    @BindView(R.id.tv_makesure)
    TextView tvMakesure;
    @BindView(R.id.ll_message)
    LinearLayout llMessage;

    private CustomerKeyboard customerKeyboard;
    private PasswordEditText passwordEditText;
    private String money;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ti_xians);
        ButterKnife.bind(this);

        actionbar.setData("提现", R.drawable.ic_lefft_white, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        money = getIntent().getStringExtra("money");
        initview();
        getData();
    }

    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, TiXianActivityS.class);
        return intent;
    }

    private void initview()
    {

        tvAllmoney.setOnClickListener(this);
        llAddcard.setOnClickListener(this);
        if (!TextUtils.isEmpty(money)){
            tvMoney.setText(money);
        }
        if (tvBankname.equals("")||tvBankname==null)
        {
            llMessage.setVisibility(View.GONE);
        }else
            {
                llMessage.setVisibility(View.VISIBLE);
            }

        etNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                    if (etNumber.getText().toString().equals("")||etNumber.getText().toString()==null
                            ||Double.valueOf(etNumber.getText().toString())<0){
                        MyToast("没有可提现金额");
                        tvMakesure.setTextColor(getResources().getColor(R.color.text51));
                        tvMakesure.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_circle_grayd));
                        tvMakesure.setOnClickListener(null);
                    }else
                        {
                            tvMakesure.setTextColor(getResources().getColor(R.color.white));
                            tvMakesure.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_circle_reds));
                            tvMakesure.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String maoney = etNumber.getText().toString();
//                                    if (maoney.equals("")||maoney==null||Double.valueOf(maoney)<0)
//                                    {
//                                        MyToast("没有可提现的金额");
//
//                                    }else
//                                    {
                                        final CommonDialog.Builder builder = new CommonDialog.Builder(TiXianActivityS.this).fullWidth().fromBottom()
                                                .setView(R.layout.dialog_customer_keyboard);
                                        builder.setOnClickListener(R.id.delete_dialog, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                builder.dismiss();
                                            }
                                        });
                                        builder.create().show();
                                        TextView tv_moneyd = (TextView)builder.getView(R.id.tv_moneyd);
                                        tv_moneyd.setText("提现金额"+maoney+"元");
                                        //自定义的数字键盘
                                        customerKeyboard = builder.getView(R.id.custom_key_board);
                                        customerKeyboard.setOnCustomerKeyboardClickListener(new CustomerKeyboard.CustomerKeyboardClickListener() {
                                            @Override
                                            public void click(String number) {
                                                //输入点击的数字
                                                passwordEditText.addPassword(number);
                                            }

                                            @Override
                                            public void delete() {
                                                //删除输入的数字
                                                passwordEditText.deleteLastPassword();
                                            }
                                        });
                                        //自定义的密码输入框
                                        passwordEditText =  builder.getView(R.id.password_edit_text);
                                        passwordEditText.setOnPasswordFullListener(new PasswordEditText.PasswordFullListener() {
                                            @Override
                                            public void passwordFull(String password) {
                                                MyToast("好了");
                                                builder.dismiss();
                                                //得到输入的密码
                                                postData(password);
                                                Log.e("test0916","密码：   "+password);
                                            }
                                        });
//                                    }
                                }
                            });
                        }
            }
        });
    }

    private void postData(String password) {
//        提现
//        @param str   token
//        @param Int   bankId      银行卡id  type为1时必传
//        @param Int   amount      金额    （加密）
//        @param Int   password    交易密码
//        @param Int   wawal_type  提现资金类型  1-返利提现  （不传为余额提现）
//        @param Int   type        提现类型  1-银行卡  2-支付宝  3-微信
//        @param Str   account     提现账户  type为2,3时必传
        Map<String,Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("bankId", id);
        map.put("amount", Base64Util.encodedString2(etNumber.getText().toString()));
        map.put("password",Base64Util.encodedString2(password));
        map.put("type", "1");
        XUtil.Post(Url.Ucenter_WITHDRAWALS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.getString("re");
                    if ("1".equals(re)) {
                        MyToast("提现成功");
                        finish();
                    }else if ("-1".equals(jsonObject.optString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFinished() {
                super.onFinished();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }


    @Override
    public void onLeftClick() {
        finish();

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }

    @OnClick({R.id.tv_allmoney, R.id.tv_makesure,R.id.ll_addcard})
    public void onViewClicked(View view) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_allmoney:
                if (tvMoney.getText().toString().equals("")||tvMoney.getText().toString()==null)
                {
                    MyToast("没有余额");
                }else
                {
                    etNumber.setText(tvMoney.getText().toString());
                }

                break;
            //选择银行
            case R.id.ll_addcard:
                Intent intents = new Intent(TiXianActivityS.this, CardChooseActivity.class);
                startActivityForResult(intents, 1);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {

            if (data != null) {
                switch (requestCode) {
                    case 1:
                        BankListBean.InfoBean item = (BankListBean.InfoBean) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        tvBankname.setText(item.getBank_name());
                        tvCardnum.setText("尾号"+item.getBank_num());
                        id = item.getBank_id();
                        break;
                }
            }
        }
    }
    private void getData() {
        Map<String,Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("page", 0+"");
        XUtil.Post(Url.Ucenter_BANKLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.getString("re");
                    if ("1".equals(re)) {
                        Gson gson = new Gson();
                        BankListBean item = gson.fromJson(result, BankListBean.class);
                        tvBankname.setText(item.getInfo().get(0).getBank_name());
                        tvCardnum.setText("尾号"+item.getInfo().get(0).getBank_num());
                        id = item.getInfo().get(0).getBank_id();
                    }else if ("-1".equals(jsonObject.optString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFinished() {
                super.onFinished();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
}
